import { Router } from 'express'
import { body } from 'express-validator'
import { asyncHandler, createError } from '../middleware/errorHandler'
import { handleValidationErrors } from '../middleware/validation'
import { UserService } from '../services/userService'
import { generateToken } from '../utils/jwt'

const router = Router()
const userService = new UserService()

// Login validation
const loginValidation = [
  body('username').notEmpty().withMessage('Username is required'),
  body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters'),
]

// Register validation
const registerValidation = [
  body('username').isLength({ min: 3 }).withMessage('Username must be at least 3 characters'),
  body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters'),
  body('email').optional().isEmail().withMessage('Please provide a valid email'),
  body('phone').optional().matches(/^1[3-9]\d{9}$/).withMessage('Please provide a valid phone number'),
]

// Login
router.post('/login', loginValidation, handleValidationErrors, asyncHandler(async (req, res) => {
  const { username, password } = req.body

  const user = await userService.authenticateUser(username, password)
  if (!user) {
    throw createError('Invalid username or password', 401)
  }

  const token = generateToken({
    userId: user.id,
    username: user.username,
    role: user.role,
  })

  res.json({
    success: true,
    data: {
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        role: user.role,
      },
      token,
    },
  })
}))

// Register
router.post('/register', registerValidation, handleValidationErrors, asyncHandler(async (req, res) => {
  const userData = req.body

  // Check if user already exists
  const existingUser = await userService.getUserByUsername(userData.username)
  if (existingUser) {
    throw createError('Username already exists', 409)
  }

  const user = await userService.createUser(userData)

  const token = generateToken({
    userId: user.id,
    username: user.username,
    role: user.role,
  })

  res.status(201).json({
    success: true,
    data: {
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        role: user.role,
      },
      token,
    },
  })
}))

// Logout
router.post('/logout', asyncHandler(async (req, res) => {
  // In a real application, you might want to blacklist the token
  // For now, we'll just return a success response
  res.json({
    success: true,
    message: 'Logged out successfully',
  })
}))

export { router as authRouter }